package com.oms.conf;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactorySecond", transactionManagerRef = "transactionManagerSecond", basePackages = {
		"com.oms.repository.second" }) /// /设置dao（repo）所在位置
public class RepositorySecondConfig {
	@Autowired
	private JpaProperties jpaProperties;
	@Autowired
	@Qualifier("secondDS")
	private DataSource secondDS;

	@Bean(name = "entityManagerSecond")
	public EntityManager entityManagerSecond(EntityManagerFactoryBuilder builder) {
		return entityManagerFactorySecond(builder).getObject().createEntityManager();
	}

	@Bean(name = "entityManagerFactorySecond")
	public LocalContainerEntityManagerFactoryBean entityManagerFactorySecond(EntityManagerFactoryBuilder builder) {
		return builder.dataSource(secondDS).properties(jpaProperties.getProperties())
				.packages("com.oms.vo.second") // 设置实体类所在位置
				.persistenceUnit("primaryPersistenceUnit").build();
	}

	@Bean(name = "transactionManagerSecond")
	PlatformTransactionManager transactionManagerSecond(EntityManagerFactoryBuilder builder) {
		return new JpaTransactionManager(entityManagerFactorySecond(builder).getObject());
	}

}
